package com.stylefeng.guns.modular.stockmanagement.service.impl;

import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.stylefeng.guns.core.datascope.DataScope;
import com.stylefeng.guns.core.shiro.ShiroKit;
import com.stylefeng.guns.modular.dto.GoodsDamageAddRequest;
import com.stylefeng.guns.modular.manager.service.IManagerGoodsService;
import com.stylefeng.guns.modular.stockmanagement.service.IGoodsDamageListService;
import com.stylefeng.guns.modular.system.model.GoodsDamage;
import com.stylefeng.guns.modular.system.dao.GoodsDamageMapper;
import com.stylefeng.guns.modular.stockmanagement.service.IGoodsDamageService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.stylefeng.guns.modular.system.model.GoodsDamageList;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author LiuXin
 * @since 2018-09-12
 */
@Service
public class GoodsDamageServiceImpl extends ServiceImpl<GoodsDamageMapper, GoodsDamage> implements IGoodsDamageService {

    @Autowired
    private IGoodsDamageListService goodsDamageListService;
    @Autowired
    private IManagerGoodsService managerGoodsService;


    @Override
    public boolean insertDamageListAndGoods(GoodsDamageAddRequest request) {
        GoodsDamage goodsDamage = new GoodsDamage();
        BeanUtils.copyProperties(request, goodsDamage);
        boolean success = this.insert(goodsDamage);
        List<GoodsDamageList> damageListList = request.getGoodsDamageList();
        damageListList.forEach(goodsDamageList -> goodsDamageList.setDamageId(goodsDamage.getId()));
        Map<Long, Integer> tempMap = damageListList.stream().collect(Collectors.toMap((GoodsDamageList::getGoodsId), (GoodsDamageList::getDamageNumber)));
        managerGoodsService.batchMinusGoodsInventory(tempMap);
        boolean insertDamageListSuccess = goodsDamageListService.insertBatch(damageListList);
        return success && insertDamageListSuccess;
    }

    @Override
    public Page<GoodsDamage> selectPageWithDataScope(Page<GoodsDamage> page, Wrapper<GoodsDamage> wrapper) {
        if (ShiroKit.isAdmin()) {
            Page<GoodsDamage> result = this.selectPage(page, wrapper);
            return result;
        } else {
            DataScope dataScope = new DataScope(ShiroKit.getDeptDataScope());
            List<GoodsDamage> result = this.baseMapper.selectPageWithDataScope(page, dataScope, wrapper.getEntity());
            page.setRecords(result);
            return page;
        }
    }
}